
import React, { PropTypes } from 'react'
import { routerRedux } from 'dva/router'
import { connect } from 'dva'
import CostList from '../components/costs/list'
import CostSearch from '../components/costs/search'
import CostModal from '../components/costs/modal'

function Costs ({ location, dispatch, costs, loading }) {
  const { list, pagination, currentItem, modalVisible, modalType, isMotion } = costs;
  const { field, keyword } = location.query;

  const costModalProps = {
    item: modalType === 'create' ? {} : currentItem,
    type: modalType,
    visible: modalVisible,
    onOk (data) {
      dispatch({
        type: `costs/${modalType}`,
        payload: data
      })
    },
    onCancel () {
      dispatch({
        type: 'costs/hideModal'
      })
    }
  }

  const costListProps = {
    dataSource: list,
    loading,
    pagination: pagination,
    location,
    isMotion,
    onPageChange (page) {
      const { query, pathname } = location
      dispatch(routerRedux.push({
        pathname: pathname,
        query: {
          ...query,
          page: page.current,
          pageSize: page.pageSize
        }
      }))
    },
    onDeleteItem (Id) {
      console.log(Id);
      dispatch({
        type: 'costs/delete',
        payload: Id
      })
    },
    onEditItem (item) {

      dispatch({
        type : 'costs/showModalAndTime',
        payload : {

        }
      });

      dispatch({
        type: 'costs/showModal',
        payload: {
          modalType: 'details',
          currentItem: item
        }
      })
    }
  }

  const costSearchProps = {
    field,
    keyword,
    isMotion,
    onSearch (fieldsValue) {
      fieldsValue.keyword.length ? dispatch(routerRedux.push({
        pathname: '/costs',
        query: {
          field: fieldsValue.field,
          keyword: fieldsValue.keyword
        }
      })) : dispatch(routerRedux.push({
        pathname: '/costs'
      }))
    },
    onAdd () {
      dispatch({
        type: 'costs/showModal',
        payload: {
          modalType: 'create'
        }
      })
    },
    switchIsMotion () {
      dispatch({type: 'costs/switchIsMotion'})
    }
  }

  const CostModalGen = () =>
    <CostModal {...costModalProps} />

  return (
    <div className='content-inner'>
      <CostSearch {...costSearchProps} />
      <CostList {...costListProps} />
      <CostModalGen />
    </div>
  )
}

Costs.propTypes = {
  costs: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func
}

export default connect(({costs, loading}) => ({costs, loading: loading.models.cost}))(Costs)
